package logic

import (
	"context"
	"fmt"
	"wet/model/cache"
	"wet/model/mysqlInit"

	"wet/wetrpc/internal/svc"
	"wet/wetrpc/wetrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateShopLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateShopLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateShopLogic {
	return &CreateShopLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 购物车添加
func (l *CreateShopLogic) CreateShop(in *wetrpc.CreateShopShopAddRequest) (*wetrpc.CreateShopShopAddResponse, error) {
	// todo: add your logic here and delete this line

	if in.Num > 10 {
		return nil, fmt.Errorf("购买数量不得超过10")
	}

	var shop mysqlInit.Shop
	mysqlInit.DB.Where("id=?", in.ShopId).Find(&shop)
	if shop.ID == 0 {
		return nil, fmt.Errorf("该商品不存在")
	}

	key := fmt.Sprintf("ShopKey:%d", in.ShopId)
	Shopcount := cache.Rdb.LLen(l.ctx, key).Val()
	if in.Num > Shopcount {
		return nil, fmt.Errorf("虚拟库存不足")
	}

	if cache.IsKeyExt(in.UserId, in.ShopId) {
		err := cache.ShopUpdates(in.UserId, in.ShopId, in.Num)
		if err != nil {
			return nil, fmt.Errorf("购物车更新失败")
		}
	} else {
		shopMap := map[string]interface{}{
			"shopName": shop.ShopName,
			"price":    shop.Price,
			"image":    shop.Image,
			"num":      shop.Num,
			"status":   shop.Status,
		}
		err := cache.ShopCares(in.UserId, in.ShopId, shopMap)
		if err != nil {
			return nil, fmt.Errorf("添加失败")
		}
	}
	return &wetrpc.CreateShopShopAddResponse{
		ShopId: int64(shop.ID),
	}, nil
}
